<template>
  <lb-layout
    v-loading="$store.getters.loading"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="#a19f9fb0;"
    :paddBottom="5"
  >
    <aps-form
      :config="apsForm.formConfig"
      :model="apsForm.formData"
      :formRef="apsForm.formRef"
      :labelWidth="apsForm.labelWidth"
      ref="form"
    ></aps-form>
    <lb-table
      class="mt20"
      :column="tableData.column"
      :data="tableData.data"
      :height="600"
      border
      pagination
      background
      layout="total, sizes, prev, pager, next, jumper"
      :page-sizes="[20, 40, 60, 80]"
      :pager-count="5"
      :current-page.sync="currentPage"
      :total="total"
      :page-size="pageSize"
      @size-change="handleSizeChange"
      @p-current-change="handleCurrentChange"
      @selection-change="handleSelectionChange"
    >
    </lb-table>
    <component
      :is="modelName"
      :id="id"
      :visible.sync="show"
      @close="close"
    ></component>
  </lb-layout>
</template>

<script>
import auth from "@/plugins/auth";
import {
  list,
  auditBudgetDeclaration,
  auditBatch,
} from "@/api/work/budgetDeclaration.js";
import { formatDate } from "@/utils/index";
import audit from "@/views/work/budgetDeclaration/components/audit.vue";
import detail from "@/views/work/budgetDeclaration/components/detail.vue";
export default {
  name: "budgetDeclaration",
  dicts: [
    "energy_declare_type",
    "energy_identify_types",
    "energy_budget_declare_status",
  ],
  components: {
    audit,
    detail,
  },
  data() {
    return {
      //弹窗
      id: "",
      modelName: "",
      multipleSelection: [],
      show: false,
      apsForm: {
        formRef: "form",
        labelWidth: "auto",
        formData: {},
        formConfig: {
          formAttr: {
            inline: true,
            size: "small",
          },
          properties: {
            sysDeptName: {
              label: "单位名称:",
              typeName: "el-input",
              clearable: true,
              placeholder: "请输入单位名称",
            },
            /* 时间日期选择器 */
            date: {
              label: "上报时间:",
              typeName: "el-date-picker",
              type: "daterange",
              size: "small",
              "value-format": "yyyy-MM-dd",
              "start-placeholder": "请选择开始日期",
              "end-placeholder": "请选择结束日期",
            },
            // declareType: {
            //   label: "填报类型",
            //   typeName: "el-select",
            //   render: (h) => {
            //     let that = this;
            //     let arr = [];
            //     that.dict?.type?.energy_declare_type.some((item) => {
            //       arr.push(item);
            //     });
            //     let valNum = that.$refs?.form?.getFieldsValue().declareType;
            //     let a = [
            //       h(
            //         "el-select",
            //         {
            //           attrs: {
            //             placeholder: "填报类型",
            //             value: valNum,
            //             clearable: true,
            //           },
            //           props: ["value"],
            //           on: {
            //             change: (value) => {
            //               that.$refs?.form?.setFieldValue("declareType", value);
            //               that.$forceUpdate();
            //             },
            //           },
            //         },
            //         [
            //           arr.map((item) => {
            //             let { label, value } = item;
            //             return h("el-option", {
            //               props: {
            //                 label,
            //                 value: value,
            //                 key: value,
            //               },
            //             });
            //           }),
            //         ]
            //       ),
            //     ];
            //     return h("div", a);
            //   },
            // },
            // status: {
            //   label: "状态",
            //   typeName: "el-select",
            //   render: (h) => {
            //     let that = this;
            //     let arr = [];
            //     that.dict?.type?.energy_budget_declare_status.some((item) => {
            //       arr.push(item);
            //     });
            //     let valNum = that.$refs?.form?.getFieldsValue().status;
            //     let a = [
            //       h(
            //         "el-select",
            //         {
            //           attrs: {
            //             placeholder: "状态",
            //             value: valNum,
            //             clearable: true,
            //           },
            //           props: ["value"],
            //           on: {
            //             change: (value) => {
            //               that.$refs?.form?.setFieldValue("status", value);
            //               that.$forceUpdate();
            //             },
            //           },
            //         },
            //         [
            //           arr.map((item) => {
            //             let { label, value } = item;
            //             return h("el-option", {
            //               props: {
            //                 label,
            //                 value: value,
            //                 key: value,
            //               },
            //             });
            //           }),
            //         ]
            //       ),
            //     ];
            //     return h("div", a);
            //   },
            // },
          },
          formSoltButton: [
            {
              label: "搜索",
              type: "primary",
              typeName: "el-button",
              size: "small",
              icon: "el-icon-search",
              click: this.handlerSearchDetail,
            },
            {
              label: "重置",
              typeName: "el-button",
              size: "small",
              icon: "el-icon-refresh-left",
              click: this.handleReset,
            },
            {
              label: "批量审批",
              typeName: "el-button",
              size: "small",
              icon: "el-icon-s-check",
              display: true,
              type: "warning",
              click: () => this.handleApproval(1),
            },
          ],
        },
      },
      currentPage: 1,
      pageSize: 20,
      total: 0,
      tableData: {
        column: [
          {
            type: "selection",
            selectable: this.selectable,
          },
          {
            prop: "sysDeptName",
            label: "单位名称",
            minWidth: 200,
            align: "center",
            showOverflowTooltip: true,
          },
          {
            prop: "declareTime",
            label: "上报时间",
            width: 200,
            align: "center",
            showOverflowTooltip: true,
          },
          {
            prop: "contact",
            label: "申报人",
            minWidth: 100,
            align: "center",
            showOverflowTooltip: true,
          },
          {
            prop: "contactNumber",
            label: "手机号码",
            minWidth: 100,
            align: "center",
            showOverflowTooltip: true,
          },
          {
            prop: "status",
            label: "状态",
            width: 200,
            align: "center",
            render: (h, scope) => {
              return (
                <div>
                  <dict-tag
                    options={this.dict.type.energy_budget_declare_status}
                    value={scope.row.status}
                  />
                </div>
              );
            },
          },
          {
            prop: "auditUsername",
            label: "审核人",
            minWidth: 150,
            align: "center",
            showOverflowTooltip: true,
          },
          {
            prop: "auditTime",
            label: "审核时间",
            minWidth: 150,
            align: "center",
            showOverflowTooltip: true,
          },
          {
            label: "操作",
            width: 180,
            fixed: "right",
            render: (h, scope) => {
              let a, b;
              if (scope.row.status == 1) {
                if (
                  auth.hasPermi("energy:budget-declare:audit:4-1") ||
                  auth.hasPermi("energy:budget-declare:audit:5-1")
                ) {
                  a = (
                    <el-button
                      type="text"
                      size="small"
                      icon="el-icon-check"
                      onClick={() => {
                        this.showModel("audit", scope.row);
                      }}
                    >
                      审核
                    </el-button>
                  );
                }
              } else if (scope.row.status == 2) {
                if (
                  auth.hasPermi("energy:budget-declare:audit:4-2") ||
                  auth.hasPermi("energy:budget-declare:audit:5-2")
                ) {
                  a = (
                    <el-button
                      type="text"
                      size="small"
                      icon="el-icon-check"
                      onClick={() => {
                        this.showModel("audit", scope.row);
                      }}
                    >
                      审核
                    </el-button>
                  );
                }
              } else if (scope.row.status == 3) {
                if (
                  auth.hasPermi("energy:budget-declare:audit:4-3") ||
                  auth.hasPermi("energy:budget-declare:audit:5-3")
                ) {
                  a = (
                    <el-button
                      type="text"
                      size="small"
                      icon="el-icon-check"
                      onClick={() => {
                        this.showModel("audit", scope.row);
                      }}
                    >
                      审核
                    </el-button>
                  );
                }
              }
              // if ([1, 2, 3, 4].includes(scope.row.status)) {
              //   a = (
              //     <el-button
              //       v-hasPermi={["energy:budget-declare:audit"]}
              //       type="text"
              //       size="small"
              //       icon="el-icon-check"
              //       onClick={() => {
              //         this.showModel("audit", scope.row);
              //       }}
              //     >
              //       审核
              //     </el-button>
              //   );
              // b = (
              //   <el-button
              //     type="text"
              //     size="small"
              //     icon="el-icon-delete"
              //     onClick={() => {
              //       this.handleUp(scope.row, -1);
              //     }}
              //     class="text-danger"
              //   >
              //     退回
              //   </el-button>
              // );
              return (
                <div>
                  {a}
                  {/* {b} */}
                  {
                    <el-button
                      v-hasPermi={["energy:budget-declare:detail"]}
                      type="text"
                      size="small"
                      icon="el-icon-view"
                      onClick={() => {
                        this.showModel("detail", scope.row);
                      }}
                    >
                      详情
                    </el-button>
                  }
                </div>
              );
            },
          },
        ],
        data: [],
      },
    };
  },
  mounted() {
    this.judgePermi();
    this.handlerSearchDetail();
  },
  methods: {
    judgePermi() {
      if (auth.hasPermi("energy:budget-declare:audit-batch")) {
        this.apsForm.formConfig.formSoltButton[2].display = false;
      }
    },
    selectable(row, index) {
      return [1, 2, 3, 4].includes(row.status);
    },
    async initData(currentPage, pageSize, data) {
      let that = this;
      let query = {
        ...data,
      };
      if (currentPage) {
        query.pageNum = currentPage;
      } else {
        query.pageNum = that.currentPage;
      }
      if (pageSize) {
        query.pageSize = pageSize;
      } else {
        query.pageSize = that.pageSize;
      }
      that.$store.commit("app/updateApiCount", "add");
      await list(query)
        .then((res) => {
          that.$store.commit("app/updateApiCount");
          if (res.code === 700) {
            that.$message.warning(res.msg);
            return false;
          }
          that.tableData.data = res.rows;
          that.total = res.total;
        })
        .catch((err) => {
          that.$store.commit("app/updateApiCount");
          // this.$message.error("系统错误,请联系管理员!错误码309001");
        });
    },
    // 多选
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleApproval(status, row) {
      let that = this;
      if (that.multipleSelection.length <= 0) {
        that.$message.warning("请至少选择一条数据审批");
        return false;
      }
      let query = {
          eventType: 4,
        },
        text = "";
      if (status === 0) {
        query.declareId = row.id;
        text = "是否确认审批" + "该条数据" + "？";
      } else if (status === 1) {
        query.declareIds = this.multipleSelection.map((el) => {
          return el.id;
        });
        text = "是否确认进行批量审批？";
      }
      this.$modal
        .confirm(text)
        .then(() => {
          this.$store.commit("app/updateApiCount", "add");
          auditBatch(query)
            .then((res) => {
              this.$store.commit("app/updateApiCount");
              if (res.code === 700) {
                that.$message.warning(res.msg);
                return false;
              }
              that.$message.success("操作成功!");
              that.handlerSearchDetail();
            })
            .catch((err) => {
              this.$store.commit("app/updateApiCount");
              // this.$message.error("系统错误,请联系管理员!错误码309008");
            });
        })
        .catch(() => {
          this.$store.commit("app/updateApiCount");
        });
    },
    // 搜索
    handlerSearchDetail(val) {
      //val===1 删除操作成功后分页边界值处理
      let currentPage = 1;
      if (val === 1) {
        if (
          this.total === (this.currentPage - 1) * this.pageSize + 1 &&
          this.total !== 0 &&
          this.currentPage > 1
        ) {
          currentPage = this.currentPage - 1;
          this.currentPage = currentPage;
        } else {
          currentPage = this.currentPage;
        }
      } else {
        currentPage = this.currentPage;
      }
      const { date, ...other } = this.$refs?.form?.getFieldsValue();
      const [startTime, endTime] = date || [];
      const data = {
        ...other,
        startTime,
        endTime,
        orderByColumn: "ebd.declare_time",
        isAsc: "desc",
      };
      this.initData(currentPage, this.pageSize, data);
    },
    // 重置
    handleReset() {
      this.$refs?.form?.resetFields();
      this.handlerSearchDetail();
    },
    handleSizeChange(val) {
      this.currentPage = 1;
      this.pageSize = val;
      this.handlerSearchDetail();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.handlerSearchDetail();
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const that = this;
      that.$modal
        .confirm("是否确认删除此数据项？")
        .then(function () {
          deleteArchitectureRoom(row.id)
            .then((res) => {
              if (res.code === 700) {
                that.$message.warning(res.msg);
                return false;
              }
              that.handlerSearchDetail();
              that.$modal.msgSuccess("删除成功");
            })
            .catch(() => {
              // this.$message.error("系统错误,请联系管理员!错误码309006");
            });
        })
        .catch(() => {});
    },
    // 退回
    handleUp(row, type) {
      const that = this;
      let text = "";
      if (type == -1) {
        text = "退回";
      }
      that
        .$confirm(`确认${text}吗?`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
        .then(() => {
          let day = formatDate(new Date(), "yyyy-MM-dd");
          auditBudgetDeclaration({
            eventType: type,
            declareId: row.id,
            eventTime: day,
          })
            .then((res) => {
              if (res.code === 700) {
                that.$message.warning(res.msg);
                return false;
              }
              that.$message({
                type: "success",
                message: "操作成功!",
              });
              that.handlerSearchDetail();
            })
            .catch((err) => {
              // this.$message.error("系统错误,请联系管理员!错误码309005");
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },
    // 弹窗
    showModel(name, params) {
      this.modelName = name;
      this.id = params?.id || "";
      setTimeout(() => {
        this.show = true;
      }, 200);
    },
    close(status) {
      this.show = false;
      setTimeout(() => {
        if (status) this.handlerSearchDetail();
      }, 200);
    },
  },
};
</script>
